<?php
/**
 * 我的
 *
 * User: kaikaic
 * Date: 2018/12/5
 * Time: 20:42
 */

namespace app\api\controller;

use app\admin\service\CityService;
use app\admin\service\TagsService;
use app\api\service\OrganizationService;
use app\psy\service\AccountService;
use app\psy\service\ConsultantExtendService;
use app\psy\service\ConsultantIndexService;
use app\psy\service\ConsultantService;
use app\psy\service\FeedbackService;
use controller\BasicApi;
use OSS\OssClient;
use service\ConfigService;
use service\SendMsgService;
use service\ToolsService;
use service\UserService;
use service\WechatService;
use think\Db;

class Me extends BasicApi {

    public function index() {
        //TODO
    }

    /**
     * 获取详细信息，是否为咨询师
     */
    public function newinfo(){
        $id = $this->request->param('id');
        $res = AccountService::getInstance()->find($id);
        $record  = ConsultantService::getInstance()->find($id,'account_id');
        $res['consult']  = $record;
        $res['apply'] = 0;
        if($record){
            if (!$record['type_ids']) {
                $record['type_ids'] = array();
            }else {
                $record['type_ids'] = unserialize($record['type_ids']);
                $record['ntype_ids'] = implode(',',$record['type_ids']);
            }
            if (!$record['goodat_ids']) {
                $record['goodat_ids'] = array();
            }else {
                $record['goodat_ids'] = unserialize($record['goodat_ids']);
                $record['ngoodat_ids'] = implode(',',$record['goodat_ids']);
            }

            if (!$record['factions_ids']) {
                $record['factions_ids'] = array();
            }else {
                $record['factions_ids'] = unserialize($record['factions_ids']);
                $record['nfactions_ids'] = implode(',',$record['factions_ids']);
            }
            if (!$record['period_ids']) {
                $record['period_ids'] = array();
            }else {
                $record['period_ids'] = unserialize($record['period_ids']);
                $record['nperiod_ids'] = implode(',',$record['period_ids']);

            }
            $tagsList = TagsService::getInstance()->getTagsArrayByAbbr("psy_qualification");
//            if ($record['qualification']) {
//                $record['qualificationtext'] = $tagsList[$record['qualification']];
//            }else {
//                $record['qualificationtext'] = "";
//            }
            $provincearea = CityService::getInstance()->single(array('area_id'=>$record['province_id']));
            $record['provincename'] = $provincearea['area_name'];
            $cityarea = CityService::getInstance()->single(array('area_id'=>$record['city_id']));
            $record['citylist'] = CityService::getInstance()->select(array('area_parent_id'=>$record['city_id']));
            $record['cityname'] = $cityarea['area_name'];

            $res['consult'] = $record;
            if($record['status']==2){
                $res['apply'] = 2;
            }
        }

        $res['area'] = CityService::getInstance()->select(array('area_parent_id'=>0));
        if($res['org_id']){
            $orginfo = OrganizationService::getInstance()->find($res['org_id']);
            $res['isshow']  = $orginfo['status'];
        }else{
            $res['isshow'] = 2;
        }
//        $consultapply = ConsultantExtendService::getInstance()->find($res['mobile'],'mobile',4);
//        if($consultapply){
//            if($consultapply['status']==2){
//                $res['apply'] = 2;
//            }else{
//                $res['apply'] = 1;
//            }
//        }else{
//            $res['apply'] = 0;
//        }

        $this->success('获取成功',$res);
    }
    /**
     * 个人信息
     *
     * psy.game.com/api/me/info?uid=274&nick_name=花儿多多K&gender=2&province_id=18&city_id=275&intro=aaaaaaaaaaaaaaaa
     */
    public function info() {
        $accountID = intval($this->getParams("uid"));           // 用户ID
        $nickName = $this->getParams("nick_name");              // 昵称
        $gender = intval($this->getParams("gender"));           // 性别，1:男,2:女
        $provinceID = intval($this->getParams("province_id"));  // 居住地-省份
        $cityID = intval($this->getParams("city_id"));          // 居住地-城市
        $address = trim($this->getParams("address"));          // 居住地-城市
        $intro = trim($this->getParams("intro"));               // 自我介绍
        $cover = trim($this->getParams("cover"));               // 自我介绍

        if (!$accountID) {
            $this->error("参数错误", 401);
        }

        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }

        $params1 = array();
        $params1['cover'] = $cover;
        if ($nickName) {
            $params1['nick_name'] = $nickName;
        }
        if ($gender) {
            $params1['gender'] = $gender;
        }
        if ($params1) {
            AccountService::getInstance()->update($params1, $accountID);
        }
        $update = array();
//        $update['province_id'] = $provinceID;
//        $update['city_id'] = $cityID;
        $update['intro'] = $intro;
//        $update['address'] = $address;
        AccountService::getInstance()->update($update, $accountID);
        $this->success("操作完成");
    }
    public function updateinfo(){
        /*
         * avatar: that.data.avatar,
            qualification: that.data.qualification,
            price: that.data.price,
            type_ids: that.data.ntype_ids,
            factions_ids: that.data.nfactions_ids,
            period_ids: that.data.nperiod_ids,
            goodat_ids: that.data.ngoodat_ids,
            islow: that.data.islow,
            forviewer: that.data.forviewer,
            worktype: that.data.worktype,
         */
        $data['id'] =  $consultid = intval($this->getParams("consultid"));
        $data['avatar'] =  $avatar = $this->getParams("avatar");
        $data['province_id'] =  $avatar = $this->getParams("province_id");
        $data['city_id'] =  $avatar = $this->getParams("city_id");

        $data['qualification'] =  $qualification = $this->getParams("qualification");
        $data['price'] =  $price = $this->getParams("price");

        $data['islow'] =  $islow = $this->getParams("islow");
        $data['forviewer'] =  $forviewer = $this->getParams("forviewer");
        $data['worktype'] =  $worktype = $this->getParams("worktype");
        $data['priceintro'] =  $priceintro = $this->getParams("priceintro");

        $type_ids = $this->getParams("type_ids");
        $factions_ids = $this->getParams("factions_ids");
        $period_ids = $this->getParams("period_ids");
        $goodat_ids = $this->getParams("goodat_ids");
        $data['qualificationphotos'] = $qualificationphotos = $this->getParams("qualificationphotos");
        $data['qualificationtext'] = $qualificationtext = $this->getParams("qualificationtext");
        $data['type_ids'] = explode(',',$type_ids);
        $data['factions_ids'] = explode(',',$factions_ids);
        $data['goodat_ids'] = explode(',',$goodat_ids);
        $data['period_ids'] = explode(',',$period_ids);

        $data['type_ids'] = serialize($data['type_ids']);
        $data['factions_ids'] = serialize($data['factions_ids']);
        $data['goodat_ids'] = serialize($data['goodat_ids']);
        $data['period_ids'] = serialize($data['period_ids']);
        $id = intval($data['id']);

        $result = ConsultantService::getInstance()->update($data, $id);
        if ($result) {
            ConsultantIndexService::getInstance()->updateTypeIndex($data);
            ConsultantIndexService::getInstance()->updateFactionsIndex($data);
            $this->success('更新成功',$result);
        }else{
            $this->error('更新失败');
        }

    }

    public function addqulificate(){
        $accountID = intval($this->getParams("account_id"));
        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }

        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('account_id'=>$accountID));
        if (!$record) {
            $this->error("没有这个咨询师", 403);
        }
        // 写入证书
        $params = array();
        $params['id'] = $record['id'];
        $params['qualificationtext'] = $this->getParams("qualificationtext");
        $params['qualificationnum'] = $this->getParams("qualificationnum");
        $params['qualificationphotos'] = $this->getParams("qualificatephotos");
        $result = ConsultantService::getInstance()->update($params,$params['id'],'id');

        if ($result>=0) {
            $this->success('操作成功');
        }else {
            $this->error("操作失败，稍后重试", 404);
        }
    }
    /**
     * 咨询师-教育经历
     *
     * psy.game.com/api/me/education
     */
    public function addeducation() {

        $accountID = intval($this->getParams("account_id"));
        $id = intval($this->getParams("id"));
        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }

        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('account_id'=>$accountID));
        if (!$record) {
            $this->error("没有这个咨询师", 403);
        }

        // 写入教育经历
        $params = array();
        $params['consultant_id'] = $record['id'];
        $params['start_date'] = $this->getParams("start_date");
        $params['end_date'] = $this->getParams("end_date");
        $params['school'] = $this->getParams("school");
        $params['major'] = $this->getParams("major");
        $params['photos'] = $this->getParams("photos");
        $params['education'] = $this->getParams("educate");
        $params['create_time'] = time();
        if($id){
            $result = ConsultantExtendService::getInstance()->update($params,$id,'id');
        }else{
            $result = ConsultantExtendService::getInstance()->insert($params);

        }
        $educations = $this->consultantEducation($record['id']);
        if ($result) {
            $this->success('操作成功',$educations);
        }else {
            $this->error("操作失败，稍后重试", 404);
        }
    }

    /**
     * 咨询师-培训与受训
     *
     * psy.game.com/api/me/train
     */
    public function addtrain() {
        $id = intval($this->getParams("id"));
        $accountID = intval($this->getParams("account_id"));
        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }

        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('account_id'=>$accountID));
        if (!$record) {
            $this->error("没有这个咨询师", 403);
        }
        // 写入教育经历
        $params = array();
        $params['consultant_id'] = $record['id'];
        $params['start_date'] = $this->getParams("start_date");
        $params['end_date'] = $this->getParams("end_date");
        $params['intro'] = $this->getParams("intro");
        $params['photos'] = $this->getParams("photos");
        $params['hours'] = $this->getParams("hours");
        $params['leader'] = $this->getParams("leader",'');
        $params['theme'] = $this->getParams("theme",'');
        $params['create_time'] = time();
        if($id){
            $result = ConsultantExtendService::getInstance()->update($params,$id,'id',1);
        }else{
            $result = ConsultantExtendService::getInstance()->insert($params, 1);
        }
        $where['consultant_id'] = $record['id'];
        $trains = $this->consultantTrain($record['id']);
        if ($result) {
            $this->success('操作成功',$trains);
        }else {
            $this->error("操作失败，稍后重试", 404);
        }
    }
    public function addpexp() {
        $id = intval($this->getParams("id"));
        $accountID = intval($this->getParams("account_id"));
        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }

        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('account_id'=>$accountID));
        if (!$record) {
            $this->error("没有这个咨询师", 403);
        }
        // 写入教育经历
        $params = array();
        $params['consultant_id'] = $record['id'];
        $params['start_date'] = $this->getParams("start_date");
        $params['end_date'] = $this->getParams("end_date");
        $params['intro'] = $this->getParams("intro");
        $params['photos'] = $this->getParams("photos");
        $params['hours'] = $this->getParams("hours");
        $params['leading'] =  $this->getParams("leading");
        $params['leadphone'] =  $this->getParams("leadphone");
        $params['leadname'] =  $this->getParams("leadname");
        $params['create_time'] = time();
        if($id){
            $result = ConsultantExtendService::getInstance()->update($params,$id,'id',5);
        }else{
            $result = ConsultantExtendService::getInstance()->insert($params, 5);
        }
        $where['consultant_id'] = $record['id'];
        $trains = $this->consultantPexp($record['id']);
        if ($result) {
            $this->success('操作成功',$trains);
        }else {
            $this->error("操作失败，稍后重试", 404);
        }
    }
    public function addsupexp() {
        $id = intval($this->getParams("id"));
        $accountID = intval($this->getParams("account_id"));
        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }

        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('account_id'=>$accountID));
        if (!$record) {
            $this->error("没有这个咨询师", 403);
        }
        // 写入教育经历
        $params = array();
        $params['consultant_id'] = $record['id'];
        $params['start_date'] = $this->getParams("start_date");
        $params['end_date'] = $this->getParams("end_date");
        $params['intro'] = $this->getParams("intro");
        $params['photos'] = $this->getParams("photos");
        $params['hours'] = $this->getParams("hours");
        $params['forwards'] =  $this->getParams("forwards");
        $params['supname'] =  $this->getParams("supname");
        $params['create_time'] = time();
        if($id){
            $result = ConsultantExtendService::getInstance()->update($params,$id,'id',6);
        }else{
            $result = ConsultantExtendService::getInstance()->insert($params, 6);
        }
        $where['consultant_id'] = $record['id'];
        $trains = $this->consultantSupexp($record['id']);
        if ($result) {
            $this->success('操作成功',$trains);
        }else {
            $this->error("操作失败，稍后重试", 404);
        }
    }
    public function del(){
        $id = intval($this->getParams("id"));
        $condition['id'] = $id;
        $type = intval($this->getParams("type"));
        $accountID = intval($this->getParams("account_id"));
        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }
        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('account_id'=>$accountID));
        if (!$record) {
            $this->error("没有这个咨询师", 403);
        }
        if($type==1){
            $res = ConsultantExtendService::getInstance()->remove($condition);
            if($res){
                $education = $this->consultantEducation($record['id']);
                $this->success('操作成功',$education);
            }else{
                $this->error("操作失败，稍后重试", 404);
            }
        }else if($type==2){
            $res = ConsultantExtendService::getInstance()->remove($condition,1);
            if($res){
                $trains = $this->consultantTrain($record['id']);
                $this->success('操作成功',$trains);
            }else{
                $this->error("操作失败，稍后重试", 404);
            }
        }else if($type==4){
            $res = ConsultantExtendService::getInstance()->remove($condition,5);
            if($res){
                $trains = $this->consultantPexp($record['id']);
                $this->success('操作成功',$trains);
            }else{
                $this->error("操作失败，稍后重试", 404);
            }
        }else if($type==5){
            $res = ConsultantExtendService::getInstance()->remove($condition,6);
            if($res){
                $trains = $this->consultantSupexp($record['id']);
                $this->success('操作成功',$trains);
            }else{
                $this->error("操作失败，稍后重试", 404);
            }
        }
    }
    private function consultantTrain($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 1);

        $trains = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] =explode(",",$records[$i]['photos']);
            $trains[] = $temp;
        }

        return $trains;
    }   

    private function consultantEducation($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where);

        $educations = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['school'] = $records[$i]['school'];
            $temp['major'] = $records[$i]['major'];
            $temp['education'] = $records[$i]['education'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] =explode(",",$records[$i]['photos']);
            $educations[] = $temp;
        }

        return $educations;
    }
    private function consultantPexp($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 5);

        $pexps = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();
            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['leading'] = $records[$i]['leading'];
            $temp['leadphone'] = $records[$i]['leadphone'];
            $temp['leadname'] = $records[$i]['leadname'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $pexps[] = $temp;
        }
        return $pexps;
    }
    private function consultantSupexp($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 6);

        $supexps = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['supname'] = $records[$i]['supname'];
            $temp['forwards'] = $records[$i]['forwards'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $supexps[] = $temp;
        }

        return $supexps;
    }
    /**
     * 咨询师-上传咨询师照片
     *
     * psy.game.com/api/me/upload
     */
    public function addphotos() {
        $accountID = intval($this->getParams("account_id"));
        $where['consultant_id'] = $consultant_id = intval($this->getParams("consultant_id"));
        $photos = $this->getParams("photos");

        $account = AccountService::getInstance()->find($accountID);
        if (!$account) {
            $this->error("没有这个账号", 402);
        }
        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('account_id'=>$accountID));
        if (!$record) {
            $this->error("没有这个咨询师", 403);
        }
        $result = ConsultantExtendService::getInstance()->remove($where, 2);
        $photsArr = explode(',',$photos);
        //TODO 图片上传处理

        for ($i = 0;$i<count($photsArr);$i++){
            $params = array();
            $params['consultant_id'] = $consultant_id;
            $params['photo'] = $photsArr[$i];
            $params['sort'] =$i+1;
            $params['create_time'] = time();
            $result = ConsultantExtendService::getInstance()->insert($params, 2);
        }
        // 写入图片记录
        if ($result) {
            $this->success('上传成功',$photsArr);
        }else {
            $this->error("操作失败，稍后重试", 404);
        }
    }
    public function uploadimg() {
        $file = $this->request->file('file');

        if ($file) {
            // 尝试执行
            try {
                $config = ConfigService::ossConfig(); //获取Oss的配置
                //实例化对象 将配置传入
                $ossClient = new OssClient($config['ID'], $config['Secret'], $config['EndPoint']);
                //这里是有sha1加密 生成文件名 之后连接上后缀

            $fileName = sha1(date('YmdHis', time()) . uniqid()) . '.png' ;
                //执行阿里云上传
                $result = $ossClient->uploadFile($config['Bucket'], $fileName, $file->getInfo()['tmp_name']);
                return $result['info']['url'];
            } catch (OssException $e) {
                return $e->getMessage();
            }
        }
    }
    /**
     * 意见反馈
     *
     * psy.game.com/api/me/feedback?account_id=274&content=2213eewrewr&mobile=13911880033
     */
    public function feedback() {
        $mobile = $this->getParams('mobile');
        if (!ToolsService::checkMobile($mobile)) {
            $this->error('请填写正确的手机号码');
        }

        $data['account_id'] = $this->getParams('account_id',0);
        $data['content'] = $this->getParams('content');
        $data['photos'] = $this->getParams('photos');
        $data['mobile'] = $mobile;
        $data['status'] = 1;
        $data['create_time'] = time();

        $result = FeedbackService::getInstance()->insert($data);
        if($result){
            $this->success('意见提交成功');
        }else{
            $this->error('意见提交失败');
        }
    }
    public function psyapply(){
        $array  = array();

        $consultid   = intval($this->getParams("consultid"));
        $data['avatar']     =  $avatar      = $this->getParams("avatar");
        $data['name']       =  $name        = $this->getParams("name");
        $data['province_id']=  $province_id = $this->getParams("province_id");
        $data['city_id']    =  $city_id     = $this->getParams("city_id");
        $data['account_id'] =  $account_id  = $this->getParams("account_id");
        $data['isread'] =  $isread  = $this->getParams("isread");
        $factions_ids       = $this->getParams("factions_ids");
        $data['factions_ids']= explode(',',$factions_ids);

        $data['type_ids']   = serialize($array);
        $data['goodat_ids'] = serialize($array);
        $data['period_ids'] = serialize($array);
        $data['factions_ids'] = serialize($data['factions_ids']);
        $id = $consultid;
//        $data['workperiod'] =$workperiod    = $this->getParams("workperiod");
        $data['workyear']   =$workyear      = $this->getParams("workyear");
        $data['personperiod']=$personperiod = $this->getParams("personperiod");
        $data['idCardphotos']=$idCardphotos = $this->getParams("idCardphotos");
        if($id){
            $result = ConsultantService::getInstance()->update($data,$id);
            if($result>=0){
                $data['id'] = $consultid;
                $this->success('提交成功',$data);
            }else{
                $this->error('提交失败');
            }
        }else{
            $data['sort'] = ConsultantService::getInstance()->getMaxSort() + 1;
            $data['status'] = 1;
            $data['create_time'] = time();
            $data['id']  = $result = ConsultantService::getInstance()->insert($data);

        }
        if($result){
            ConsultantIndexService::getInstance()->updateFactionsIndex($data);
            $this->success('提交成功',$data);
        }else{
            $this->error('提交失败');
        }
    }
    public function getopenid()
    {
        $code = $this->getParams("code");
        $arr = WechatService::getOpenId($code);
        $this->success('',$arr);
    }
    /**
     * 登陆
     * http://fri.game.com/index/User/login?mobile=xxx&pass=xxx
     */
    public function login() {
        $mobile = $this->getParams('mobile');
        if (!$mobile) {
            $this->error("手机号码不能为空");
        }
        $pass = $this->getParams('pass');
        if (!$pass) {
            $this->error("密码不能为空");
        }
        $user = UserService::dologin($mobile);
        if($user){
            $passArr = encrypt($pass, $user['salt']);
            //$userInfo['ordernum'] = OrderService::orderAllNum($user['id']);
            if($user && $passArr['pass'] == $user['password']) {
                $this->success('获取成功',$user);
            } else {
                $this->error("手机号或密码不正确");
            }
        }else{
            $this->error("手机号不正确");
        }

    }

    public function resetPassword(){

        $mobile = $this->request->param('mobile');
        if (!$mobile) {
            $this->error( "手机号码不能为空");
        }
        $oldpass = $this->request->param('oldpass');
        if (!$oldpass) {
            $this->error( "旧密码不能为空");
        }
        $newpass = $this->request->param('newpass');
        if (!$newpass) {
            $this->error( "新密码不能为空");
        }
        $user = UserService::dologin($mobile);

        $passArr = encrypt($oldpass, $user['salt']);
        if($user && $passArr['pass'] == $user['password']) {

            $newpassArr = encrypt($newpass, $user['salt']);
            $userdata['password'] = $newpassArr['pass'];
            $update = UserService::save($userdata,$user['id']);
            if($update){
                $this->success( '修改密码成功',$user);
            }else{
                $this->error('修改密码失败');
            }
        }else{
            $this->error("手机号码或者旧密码错误");
        }
    }
    /*
        * 注册
        * http://fri.game.com/index/Use r/login?mobile=xxx
        */
    public function reg() {
        $mobile = $this->request->param('mobile');
        $nick_name = $this->request->param('nick_name');
        $avatarUrl = $this->request->param('avatarUrl');
        $openid = $this->request->param('openid');
        if (!$mobile) {
            $this->error("手机号码不能为空");
        }
        $c = UserService::doreg($mobile);
        if($c) {
            $this->success('该手机号已存在');
        }else{
            $uid = UserService::createUser($nick_name,$mobile,$avatarUrl,$openid);
            if($uid){
                $userInfo = UserService::find($uid);
                $this->success( '注册成功,默认密码111111',$userInfo);
            }else{
                $this->error('该微信号已绑定账号');
            }

        }
    }
    public function codelogin() {
        $mobile = $this->request->param('mobile');

      $userInfo = UserService::dologin($mobile);
        if($userInfo) {
            $this->success('登录成功',$userInfo);
        }else{
           $this->error('账号不存在');

        }
    }
    public function doopenidlogin(){
        $openid = $this->request->param('openid');
        $res = AccountService::getInstance()->find($openid,'openid');
        if($res){
            $this->success('登录成功',$res);
        }else{
            $this->error('微信登录失败，请先注册');
        }
    }

    public function sendmessage() {
        $phone = $this->request->param('mobile');
        if (!$phone) {
            $this->error('参数错误');
        }

        if (!$this->checkMobile($phone)) {
            $this->error("手机号码错误", 401);
        }

        $send = session('validate_code');
//        if (!empty($send) && $send['time'] > time() && $send['sender'] == $phone) {
//            //在有效期范围内 相同号码不再发送
//            return json(array('status' => -1, 'msg' => '规定时间内,不要重复发送验证码','res'=>$send));
//        }

        $resa = self::sendSms($phone);
        $res = array('status' => 1, 'msg' => '发送成功','res'=>$resa);
        return json($res);
    }
    private function checkMobile($mobile) {
        return preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $mobile);
    }
    /**
     * 发送短信
     */
    public function sendSms($phone) {
        $sms_time_out =  1800;
        $code = mt_rand(1000, 9999);
        cookie("code",$code);
        $params = array ();

        $info['code'] = $code;
        $info['is_check'] = 0;
        $info['time'] = time() + $sms_time_out; //有效验证时间
        $info['sender'] = $phone;

        session('validate_code', $info);
        $AccountInfo = SendMsgService::account();
        $params['action'] = 'send';
        $params['userid'] = $AccountInfo['user_id'];
        $params['account'] = $AccountInfo['user'];
        $params['password'] = $AccountInfo['pwd'];
        $params['mobile'] = $phone;
        $params['content'] = '欢迎来到九州心理咨询,您的注册验证码为'.$code.',有效时间为30分钟 【九州心理咨询】';
        $params['sendTime'] = '';
        $params['extno'] = '';
        $res =  self::send_post($AccountInfo['url'],$params);
        return $info;

    }

    function send_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    public function getmark(){
        $size = 5;
        $page = intval($this->request->param("page"),1);
        $limit = "($page-1)*$size,$size";
        $condition['account_id'] = $id =$this->request->param('id');
        $condition['type'] =$type =  $this->request->param('type');
        $res = Db::name('psy_follow')->where($condition)->column('target_id');
        $value = implode(",",$res);
        if($type=='org'){
            $cond['id'] = array("in",$value);
//            OrganizationService::getInstance()->selectlimit($cond, 0,'',$limit);
            $records =   Db::name("psy_organization")->whereIn('id',$value)->limit($limit)->select();
            foreach ($records as $key =>&$item){
                $city = CityService::getInstance()->single(array('area_id'=>$item['city_id']));
                $item['city'] = $city['area_name'];
                $consultType = $this->readCategoryConfig("psy_price");
                $organizationType = $this->readCategoryConfig("organization");
                $item['pricename'] = $consultType[$item['price']];
                $item['category_name'] = $organizationType[$item['category_id']];
            }
        }else{
            $cond['status'] = 2;
            $cond['id'] = array("in",$value);
            $limit = "($page-1)*$size,$size";
            $records =   Db::name("PsyConsultant")->whereIn('id',$value)->limit($limit)->select();
            foreach ($records as $key =>&$item){

                $city = CityService::getInstance()->single(array('area_id'=>$item['city_id']));
                $item['city'] = $city['area_name'];
                // 资质
//                $tagsList = TagsService::getInstance()->getTagsArrayByAbbr("psy_qualification");
//                if ($item['qualification']) {
//                    $item['qualification'] = $tagsList[$item['qualification']];
//                }else {
//                    $item['qualification'] = "";
//                }
                $item['qualification'] = $item['qualificationtext'];
                $consultType = $this->readCategoryConfig("psy_consult");
                $type = unserialize($item['type_ids']);
                $typeStr = "";
                foreach ($type as $key) {
                    $typeStr .= $consultType[$key] . "/";
                }
                $item['type_txt'] = trim($typeStr, "/");
            }
        }
        $this->success('获取成功',$records);

    }


    public function psytags(){
        $id = $this->request->param('id', '');
        $record  = array();
        if (empty($id)) {
        }else{
            $record = ConsultantService::getInstance()->find($id);
            if (empty($record)) {
                $this->error('记录不存在，请重新操作!');
            }else{
                if (!$record['type_ids']) {
                    $record['type_ids'] = array();
                }else {
                    $record['type_ids'] = unserialize($record['type_ids']);
                    $record['ntype_ids'] = implode(',',$record['type_ids']);
                }
                if (!$record['goodat_ids']) {
                    $record['goodat_ids'] = array();
                }else {
                    $record['goodat_ids'] = unserialize($record['goodat_ids']);
                    $record['ngoodat_ids'] = implode(',',$record['goodat_ids']);
                }

                if (!$record['factions_ids']) {
                    $record['factions_ids'] = array();
                }else {
                    $record['factions_ids'] = unserialize($record['factions_ids']);
                    $record['nfactions_ids'] = implode(',',$record['factions_ids']);
                }
                if (!$record['period_ids']) {
                    $record['period_ids'] = array();
                }else {
                    $record['period_ids'] = unserialize($record['period_ids']);
                    $record['nperiod_ids'] = implode(',',$record['period_ids']);

                }
//                $tagsList = TagsService::getInstance()->getTagsArrayByAbbr("psy_qualification");
//                if ($record['qualification']) {
//                    $record['qualificationtext'] = $tagsList[$record['qualification']];
//                }else {
//                    $record['qualificationtext'] = "";
//                }
                if($record['qualificationphotos']){
                    $record['qualificationphotos'] = explode(',',$record['qualificationphotos']);
                }else{
                    $record['qualificationphotos'] = array();

                }
                if($record['idCardphotos']){
                    $record['idCardphotos'] = explode(',',$record['idCardphotos']);
                }else{
                    $record['idCardphotos'] = array();

                }
                $provincearea = CityService::getInstance()->single(array('area_id'=>$record['province_id']));
                $record['provincename'] = $provincearea['area_name'];
                $cityarea = CityService::getInstance()->single(array('area_id'=>$record['city_id']));
                $record['citylist'] = CityService::getInstance()->select(array('area_parent_id'=>$record['city_id']));
                $record['cityname'] = $cityarea['area_name'];

            }


        }
        $res['area'] = CityService::getInstance()->select(array('area_parent_id'=>0));
        $res['record'] = $record;
        $res['psy_consult']  =   $psy_consult=$this->readCategoryConfig("psy_consult");
        $res['tag_list']  =   $tag_list=TagsService::getInstance()->listTagsByCategory("psy_qualification");
        $res['tags_time']  =   $tags_time=TagsService::getInstance()->getTagsArrayByAbbr("tags_time");
        $res['tag_type_list']  =   $tag_type_list=TagsService::getInstance()->getTagsArrayByAbbr("tags_type");
        $res['factions_list']  =   $factions_list=TagsService::getInstance()->getTagsArrayByAbbr("tags_factions");
       $this->success('获取成功',$res);
    }
}